package com.toshiba.splashjetinkbd;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.denzcoskun.imageslider.ImageSlider;
import com.denzcoskun.imageslider.constants.ScaleTypes;
import com.denzcoskun.imageslider.models.SlideModel;
import com.toshiba.splashjetinkbd.api.ApiClient;
import com.toshiba.splashjetinkbd.api.ApiInterface;
import com.toshiba.splashjetinkbd.api.Product;
import com.toshiba.splashjetinkbd.db.AppDatabase;
import com.toshiba.splashjetinkbd.model.CartItem;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProductDetailsFragment extends Fragment {

    private static final String TAG = "ProductDetailsFragment";
    private static final String ARG_PRODUCT_ID = "PRODUCT_ID";

    // UI Components
    private ImageSlider imageSlider;
    private TextView tvDetailProductName, tvDetailProductPrice, tvDetailProductRegularPrice,
            tvDetailProductModels, tvDetailProductDescription, tvDetailProductSpecification,
            tvDetailProductBrand, tvDetailProductCategory;
    private TextView titleModels, titleDescription, titleSpecification;
    private ImageButton btnShare;
    private Button btnAddToCart, btnBuyNow, btnWhatsappOrder, btnAddReview;
    private RatingBar rbProductRating;
    
    private Product currentProduct;

    // Default Constructor
    public ProductDetailsFragment() {
        // Required empty public constructor
    }

    // Static method to create a new instance with arguments easily
    public static ProductDetailsFragment newInstance(int productId) {
        ProductDetailsFragment fragment = new ProductDetailsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PRODUCT_ID, productId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.activity_product_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 1. Setup Toolbar
        Toolbar toolbar = view.findViewById(R.id.toolbar);
        if (getActivity() != null) {
            ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
            if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
                ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
            }
            // Handle Back Button click
            toolbar.setNavigationOnClickListener(v -> {
                if (getParentFragmentManager().getBackStackEntryCount() > 0) {
                    getParentFragmentManager().popBackStack();
                } else {
                    requireActivity().onBackPressed();
                }
            });
        }

        // 2. Initialize Views
        initializeViews(view);

        // 3. Get Product ID from Arguments
        if (getArguments() != null) {
            int productId = getArguments().getInt(ARG_PRODUCT_ID, -1);
            Log.d(TAG, "onViewCreated: Received Product ID: " + productId);
            
            if (productId != -1) {
                fetchProductDetails(productId);
            } else {
                Toast.makeText(getContext(), "Error: Product ID missing", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initializeViews(View view) {
        imageSlider = view.findViewById(R.id.image_slider_detail);
        tvDetailProductName = view.findViewById(R.id.tvDetailProductName);
        tvDetailProductBrand = view.findViewById(R.id.tvDetailProductBrand);
        tvDetailProductCategory = view.findViewById(R.id.tvDetailProductCategory);
        rbProductRating = view.findViewById(R.id.rbProductRating);
        tvDetailProductPrice = view.findViewById(R.id.tvDetailProductPrice);
        tvDetailProductRegularPrice = view.findViewById(R.id.tvDetailProductRegularPrice);
        tvDetailProductModels = view.findViewById(R.id.tvDetailProductModels);
        tvDetailProductDescription = view.findViewById(R.id.tvDetailProductDescription);
        tvDetailProductSpecification = view.findViewById(R.id.tvDetailProductSpecification);
        
        btnShare = view.findViewById(R.id.btnShare);
        btnAddToCart = view.findViewById(R.id.btnAddToCart);
        btnBuyNow = view.findViewById(R.id.btnBuyNow);
        btnWhatsappOrder = view.findViewById(R.id.btnWhatsappOrder);
        btnAddReview = view.findViewById(R.id.btnAddReview);

        titleModels = view.findViewById(R.id.titleModels);
        titleDescription = view.findViewById(R.id.titleDescription);
        titleSpecification = view.findViewById(R.id.titleSpecification);
    }

    private void fetchProductDetails(int productId) {
        // Check if attached to context to avoid crashes
        if (getContext() == null) return;

        ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
        Call<Product> call = api.getProductDetails(productId);

        call.enqueue(new Callback<Product>() {
            @Override
            public void onResponse(@NonNull Call<Product> call, @NonNull Response<Product> response) {
                if (!isAdded()) return; // Fragment checks

                if (response.isSuccessful() && response.body() != null) {
                    currentProduct = response.body();
                    populateUi(currentProduct);
                } else {
                    Toast.makeText(getContext(), "Failed to load details", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<Product> call, @NonNull Throwable t) {
                if (isAdded()) {
                    Toast.makeText(getContext(), "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void populateUi(Product product) {
        tvDetailProductName.setText(product.getName());
        tvDetailProductBrand.setText(String.valueOf(product.getBrandName()));
        tvDetailProductCategory.setText(product.getCategory());
        rbProductRating.setRating(product.getRating());

        tvDetailProductPrice.setText("৳ " + product.getOffer_price());
        tvDetailProductRegularPrice.setText("৳ " + product.getRegular_price());
        tvDetailProductRegularPrice.setPaintFlags(tvDetailProductRegularPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

        setupImageSlider(product.getImage_url(), product.getGallery_images());

        setTextOrHide(titleModels, tvDetailProductModels, product.getModels());
        setTextOrHide(titleDescription, tvDetailProductDescription, product.getDescription());
        setTextOrHide(titleSpecification, tvDetailProductSpecification, product.getSpecification());

        // Buttons
        btnShare.setOnClickListener(v -> shareProduct(product));
        btnAddToCart.setOnClickListener(v -> addToCart(false));
        btnBuyNow.setOnClickListener(v -> buyNow());
        btnWhatsappOrder.setOnClickListener(v -> orderOnWhatsApp(product));
        btnAddReview.setOnClickListener(v -> Toast.makeText(getContext(), "Coming Soon", Toast.LENGTH_SHORT).show());
    }

    private void setTextOrHide(TextView titleView, TextView contentView, String text) {
        if (text != null && !text.trim().isEmpty() && !text.equalsIgnoreCase("null")) {
            titleView.setVisibility(View.VISIBLE);
            contentView.setVisibility(View.VISIBLE);
            contentView.setText(text);
        } else {
            titleView.setVisibility(View.GONE);
            contentView.setVisibility(View.GONE);
        }
    }

    private void setupImageSlider(String mainImageUrl, String galleryImages) {
        List<SlideModel> imageList = new ArrayList<>();

        if (mainImageUrl != null && !mainImageUrl.isEmpty()) {
            imageList.add(new SlideModel(mainImageUrl, ScaleTypes.CENTER_INSIDE));
        }

        if (galleryImages != null && !galleryImages.isEmpty()) {
            String[] images = galleryImages.split(",");
            for (String img : images) {
                if (!img.trim().isEmpty()) {
                    imageList.add(new SlideModel(img.trim(), ScaleTypes.CENTER_INSIDE));
                }
            }
        }
        imageSlider.setImageList(imageList);
    }

    private void addToCart(boolean navigateToCart) {
        if (currentProduct == null || getContext() == null) return;

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            AppDatabase db = AppDatabase.getInstance(requireContext());
            CartItem existingItem = db.cartDao().getCartItemByProductId(currentProduct.getId());

            if (existingItem != null) {
                existingItem.setQuantity(existingItem.getQuantity() + 1);
                db.cartDao().update(existingItem);
            } else {
                CartItem newItem = new CartItem(
                        currentProduct.getId(),
                        currentProduct.getName(),
                        currentProduct.getOffer_price(),
                        currentProduct.getImage_url(),
                        1
                );
                db.cartDao().insert(newItem);
            }

            if (getActivity() != null) {
                requireActivity().runOnUiThread(() -> {
                    if (navigateToCart) {
                        Toast.makeText(getContext(), "Proceeding to Checkout...", Toast.LENGTH_SHORT).show();
                        // Intent intent = new Intent(getContext(), CartActivity.class);
                        // startActivity(intent);
                    } else {
                        Toast.makeText(getContext(), "Added to Cart!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void buyNow() {
        addToCart(true);
    }

    private void shareProduct(Product product) {
        String shareBody = "Check out this product: " + product.getName() + 
                           "\nPrice: ৳" + product.getOffer_price() + 
                           "\n\n" + product.getDescription();

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Product: " + product.getName());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }

    private void orderOnWhatsApp(Product product) {
        String phoneNumber = "+8801611482988"; 
        String message = "Hello, I want to order:\n" + product.getName() + " (ID: " + product.getId() + ")";

        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" + URLEncoder.encode(message, "UTF-8");
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(getContext(), "WhatsApp not found", Toast.LENGTH_SHORT).show();
        }
    }
}